/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modelo.dao;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import modelo.Sguf;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import modelo.Sgpais;
import modelo.dao.exceptions.IllegalOrphanException;
import modelo.dao.exceptions.NonexistentEntityException;
import modelo.dao.exceptions.PreexistingEntityException;

/**
 *
 * @author Marcio
 */
public class SgpaisJpaController implements Serializable {

    public SgpaisJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Sgpais sgpais) throws PreexistingEntityException, Exception {
        if (sgpais.getSgufCollection() == null) {
            sgpais.setSgufCollection(new ArrayList<Sguf>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Collection<Sguf> attachedSgufCollection = new ArrayList<Sguf>();
            for (Sguf sgufCollectionSgufToAttach : sgpais.getSgufCollection()) {
                sgufCollectionSgufToAttach = em.getReference(sgufCollectionSgufToAttach.getClass(), sgufCollectionSgufToAttach.getSgufPK());
                attachedSgufCollection.add(sgufCollectionSgufToAttach);
            }
            sgpais.setSgufCollection(attachedSgufCollection);
            em.persist(sgpais);
            for (Sguf sgufCollectionSguf : sgpais.getSgufCollection()) {
                Sgpais oldSgpaisOfSgufCollectionSguf = sgufCollectionSguf.getSgpais();
                sgufCollectionSguf.setSgpais(sgpais);
                sgufCollectionSguf = em.merge(sgufCollectionSguf);
                if (oldSgpaisOfSgufCollectionSguf != null) {
                    oldSgpaisOfSgufCollectionSguf.getSgufCollection().remove(sgufCollectionSguf);
                    oldSgpaisOfSgufCollectionSguf = em.merge(oldSgpaisOfSgufCollectionSguf);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSgpais(sgpais.getCodpais()) != null) {
                throw new PreexistingEntityException("Sgpais " + sgpais + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Sgpais sgpais) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sgpais persistentSgpais = em.find(Sgpais.class, sgpais.getCodpais());
            Collection<Sguf> sgufCollectionOld = persistentSgpais.getSgufCollection();
            Collection<Sguf> sgufCollectionNew = sgpais.getSgufCollection();
            List<String> illegalOrphanMessages = null;
            for (Sguf sgufCollectionOldSguf : sgufCollectionOld) {
                if (!sgufCollectionNew.contains(sgufCollectionOldSguf)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Sguf " + sgufCollectionOldSguf + " since its sgpais field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Sguf> attachedSgufCollectionNew = new ArrayList<Sguf>();
            for (Sguf sgufCollectionNewSgufToAttach : sgufCollectionNew) {
                sgufCollectionNewSgufToAttach = em.getReference(sgufCollectionNewSgufToAttach.getClass(), sgufCollectionNewSgufToAttach.getSgufPK());
                attachedSgufCollectionNew.add(sgufCollectionNewSgufToAttach);
            }
            sgufCollectionNew = attachedSgufCollectionNew;
            sgpais.setSgufCollection(sgufCollectionNew);
            sgpais = em.merge(sgpais);
            for (Sguf sgufCollectionNewSguf : sgufCollectionNew) {
                if (!sgufCollectionOld.contains(sgufCollectionNewSguf)) {
                    Sgpais oldSgpaisOfSgufCollectionNewSguf = sgufCollectionNewSguf.getSgpais();
                    sgufCollectionNewSguf.setSgpais(sgpais);
                    sgufCollectionNewSguf = em.merge(sgufCollectionNewSguf);
                    if (oldSgpaisOfSgufCollectionNewSguf != null && !oldSgpaisOfSgufCollectionNewSguf.equals(sgpais)) {
                        oldSgpaisOfSgufCollectionNewSguf.getSgufCollection().remove(sgufCollectionNewSguf);
                        oldSgpaisOfSgufCollectionNewSguf = em.merge(oldSgpaisOfSgufCollectionNewSguf);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Short id = sgpais.getCodpais();
                if (findSgpais(id) == null) {
                    throw new NonexistentEntityException("The sgpais with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Short id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sgpais sgpais;
            try {
                sgpais = em.getReference(Sgpais.class, id);
                sgpais.getCodpais();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The sgpais with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Sguf> sgufCollectionOrphanCheck = sgpais.getSgufCollection();
            for (Sguf sgufCollectionOrphanCheckSguf : sgufCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Sgpais (" + sgpais + ") cannot be destroyed since the Sguf " + sgufCollectionOrphanCheckSguf + " in its sgufCollection field has a non-nullable sgpais field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(sgpais);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Sgpais> findSgpaisEntities() {
        return findSgpaisEntities(true, -1, -1);
    }

    public List<Sgpais> findSgpaisEntities(int maxResults, int firstResult) {
        return findSgpaisEntities(false, maxResults, firstResult);
    }

    private List<Sgpais> findSgpaisEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Sgpais.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Sgpais findSgpais(Short id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Sgpais.class, id);
        } finally {
            em.close();
        }
    }

    public int getSgpaisCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Sgpais> rt = cq.from(Sgpais.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
